package com.yeswater.algorithm.leetcode.hot100;

import com.yeswater.algorithm.leetcode.ListNode;

public class Code2 {

    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode dummyNode = new ListNode();
            ListNode cur = dummyNode;
            int tmp = 0; // 进位

            // 两个数还有余位或者有进位
            while (l1 != null || l2 != null || tmp != 0) {
                int val1 = l1 == null ? 0 : l1.val;
                int val2 = l2 == null ? 0 : l2.val;
                tmp = val1 + val2 + tmp;
                ListNode node = new ListNode(tmp % 10);
                cur.next = node;
                cur = cur.next;

                tmp /= 10;

                if (l1 != null) {
                    l1 = l1.next;
                }
                if (l2 != null) {
                    l2 = l2.next;
                }

            }
            return dummyNode.next;
        }
    }

}
